# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time

import wizard
import netsvc
import pooler
from osv.orm import browse_record

from osv import osv, fields

class wizard_create_payment(wizard.interface):
    #def action_expense_create_payment(self, cr, uid, ids, *args):
    def _create_payment(self, cr, uid, data, context):
        order_obj = pooler.get_pool(cr.dbname).get('purchase.order')
        #pck_obj = pooler.get_pool(cr.dbname).get('stock.picking')
        
        def payment_detail_create(project_id,budget_id,budgetname,amount,adv,retention,progress):
            progress_amount = amount/100.0
            adv_amount = - adv * amount/100.0
            retention_amount = - retention * amount/100.0
            return (0, False, {
                'project_id':project_id,
                'budget_id':budget_id,
                'description':budgetname,
                'amount': amount,
                'advanced_amount':adv_amount,
                'retention_amount':retention_amount
            })
        res = False
        ids = []
        try:
            ids = data['ids']
        except:
            ids = [data['id']]
        tmp_ids = ",".join(map(str,ids))

        cr.execute("Select \
                            distinct purchase_id \
                    from stock_picking \
                    where purchase_id in (Select id from purchase_order where state not in ('draft','cancel','done')) and \
                    id in (%s)" % tmp_ids)
        ids = cr.fetchall()
        
        cr.execute('Select id from stock_picking where coalesce(check_payment,0)>0 and id in (%s)' % tmp_ids)
        check_payment = cr.fetchone()
        if check_payment:
            raise osv.except_osv("KDVN Warning","One or more packing already created payment !")
        cr.execute("Select \
                            trim(sum(note || ' ')) \
                    from stock_picking \
                    where id in (%s)" % tmp_ids)
        rop_note_lst = cr.fetchone()
        rop_description=''
        if rop_note_lst:
            rop_description ='Payment for ' +  rop_note_lst[0]
        #raise osv.except_osv("E",ids) 
        for o in order_obj.read(cr, uid, ids,['order_payment_term_ids',
                                         'order_line',
                                         'tax_per',
                                         'tax_amount',
                                         'partner_id',
                                         'currency_id',
                                         'project_id',
                                         'id','rop_ids','notes'
                                         ]):        
#            if o['rop_ids']:
#                raise osv.except_osv('Warning','Request of payment already exist')
            cr.execute("Select\
                            sum(coalesce(sm.product_qty,0)*coalesce(pol.price_unit,0)) as total_amount\
                        from\
                            stock_move sm\
                        left join\
                            purchase_order_line pol on purchase_line_id = pol.id\
                        where sm.picking_id in (%s)\
                        group by\
                            pol.order_id" % tmp_ids)
            tmp_one = cr.fetchone()
            #raise osv.except_osv("E",tmp_one)
            if tmp_one:
                subtotal = tmp_one[0]
            payment_details = []
            adv_amount = 0.0
            retention_amount = 0.0
            adv = 0.0
            retention = 0.0
            progress = 0.0
            for po_term in pooler.get_pool(cr.dbname).get('kdvn.po.payment.term.line').read(cr,uid,o['order_payment_term_ids'],['type','value_amount']):
                if po_term['type']=='adv':
                    adv_amount = po_term['value_amount']*subtotal/100
                    adv = po_term['value_amount']
                elif po_term['type']=='re':
                    retention_amount = po_term['value_amount']*subtotal/100
                    retention = po_term['value_amount']
                else:                    
                    progress = po_term['value_amount']
#            for po_term in pooler.get_pool(cr.dbname).get('kdvn.po.payment.term.line').read(cr,uid,o['order_payment_term_ids'],['type','value_amount','name']):
#                if po_term['type']<>'p':
#                    this_tax_amount = 0.0
#                    this_progress_amount = 0.0
#                    if po_term['type']=='adv':
#                        this_retention_amount = 0.0
#                        this_adv_amount = adv_amount
#                    else:
#                        this_adv_amount = 0.0
#                        this_retention_amount = retention_amount
#                else:
                    #progress = po_term['value_amount']
                this_tax_amount = subtotal*o['tax_per']/100.0
                this_progress_amount = subtotal
                this_adv_amount = - adv_amount
                this_retention_amount = - retention_amount
                payment_details = []
                cr.execute("Select\
                                pol.project_id,\
                                kdvn_budget_id,\
                                abp.name as budget_name,\
                                sum(coalesce(sm.product_qty,0)*coalesce(pol.price_unit,0)) as total_amount\
                            from\
                                stock_picking sp\
                            left join\
                                stock_move sm on sp.id = sm.picking_id\
                            left join\
                                purchase_order_line pol on purchase_line_id = pol.id\
                            left join\
                                product_product pp on pol.product_id = pp.id\
                            left join\
                                account_budget_post abp on kdvn_budget_id = abp.id\
                            where sp.purchase_id in (%s)\
                            group by\
                                pol.project_id,\
                                kdvn_budget_id,\
                                abp.name" % o['id'])
                for project_id,budget_id,budgetname,amount in cr.fetchall():
                #self.pool.get('purchase.order.line').read(cr,uid,o['order_line'],['product_id','project_id','product_uom','price_subtotal2','name']):
                    #pr_id = budget_id
                    #prj_id = o.project_id.id
                    #raise osv.except_osv("E","%s-%s-%s" %(adv,retention,progress))
                    payment_details.append(payment_detail_create(project_id,budget_id,budgetname,amount,adv,retention,progress))
    
    #                if o['notes']:
    #                    new_description = po_term['name'] + "\n"+  o['notes']
    #                else:
    #                    new_description = po_term['name']
                                 
                payment = {
                    'paymentno':'',
                    'amount':this_progress_amount,
                    'tax_amount':this_tax_amount,
                    'advanced_amount':this_adv_amount,
                    'retention_amount':this_retention_amount,
                    'tax_per':int(o['tax_per']) or 0,
                    'supplier_id': o['partner_id'][0],
                    'currency_id': o['currency_id'][0],
                    'detail_ids': payment_details,
                    'order_id':o['id'], # For KDVN,
                    'project_id':o['project_id'][0],
                    'description':rop_description#po_term['name'] + "\n"+  o['notes']
                    }
                #raise osv.except_osv("E",payment)
                kdvn_rop_id = pooler.get_pool(cr.dbname).get('kdvn.request.of.payment').create(cr, uid, payment)
                cr.execute("Update stock_picking set check_payment=%d where id in (%s)" % (kdvn_rop_id,tmp_ids))
            value = {
                'domain': "[('id', '='," + str(kdvn_rop_id) +")]",
                'name': 'Payment to Supplier',
                'view_type': 'form',
                'view_mode': 'tree,form',
                'res_model': 'kdvn.request.of.payment',
                'view_id': False,
                'type': 'ir.actions.act_window'
        }      
        return value
        
    states = {
        'init' : {
            'actions' : [],
            'result' : {'type':'action','action':_create_payment,'state':'end'}
        }
    }
wizard_create_payment("kdvn.po.packing.to.payment")

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

